
#import "UnderLinePolicyController.h"
#import "TopButtonsView.h"
#import "PolicyCell.h"
#import "UnderLinePolicyMode.h"
#import "DetailPolicyController.h"
#import "PolicyListModel.h"
#import "UnderLineSearchViewController.h"

@interface UnderLinePolicyController ()<UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) TopButtonsView* topView;
@property (nonatomic, strong) UITableView* tableView;
@property (nonatomic, strong) NSArray* titles;
//记录滚动视图的按钮位置
@property (nonatomic, unsafe_unretained) NSInteger buttonIndex;


@property (nonatomic, strong) ShowNoNetworkView* workView;
@property (nonatomic, strong) NSMutableArray* products;
//用一个数来记录用户上拉加载的次数
@property (nonatomic, unsafe_unretained) NSInteger slCount;
@property (nonatomic, strong) MJRefreshAutoGifFooter *footer;
@property (nonatomic, strong) MJRefreshGifHeader *header;


@end

@implementation UnderLinePolicyController

- (NSMutableArray*)products
{
    if (!_products)
    {
        _products = [NSMutableArray array];
    }
    return _products;
}


- (TopButtonsView*)topView
{
    if (!_topView)
    {
        _topView = [[TopButtonsView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, 40)];
        _topView.myScrollView.delegate = self;
        _topView.backgroundColor = ClEARColor;
    }
    return _topView;
}

- (UITableView*)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40, UISCREENWEITH, UISCREENHEIGHT - 40 - NavigationBarHeight - StatusBarHeight) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = F3F3F3Color;
    }
    return _tableView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.buttonIndex = 0;
    self.slCount = 1;
    self.navigationController.navigationBar.hidden = NO;
    self.view.backgroundColor = FFFFFFColor;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:LoadImage(@"back1") style:UIBarButtonItemStylePlain target:self action:@selector(popRootVC)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:LoadImage(@"seacher") style:UIBarButtonItemStylePlain target:self action:@selector(search)];
    self.title = @"保单管理";
    self.header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    self.header.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.header = self.header;
    self.footer = [MJRefreshAutoGifFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    // Set footer
    self.tableView.footer = self.footer;
    [self.footer setHidden:YES];
    //请求数据
    [self postFastBDListWithPageSize:self.slCount withPages:10 withType:[NSString stringWithFormat:@"%ld",(long)self.buttonIndex]];
}

#pragma mark  //弹出搜索页面
- (void)search
{
    NSLog(@"弹出搜索页面........");
    UnderLineSearchViewController* searchVC = [[UnderLineSearchViewController alloc]init];
    searchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
}

//下拉刷新
- (void)loadNewData
{
    NSLog(@"下拉刷新");
    self.slCount = 1;
    [self.products removeAllObjects];
    [self.tableView.header beginRefreshing];
    [self.tableView.footer resetNoMoreData];
    [self removeWorkView];
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        //请求数据
        [self postFastBDListWithPageSize:self.slCount withPages:10 withType:[NSString stringWithFormat:@"%ld",(long)self.buttonIndex]];
    });
}

//上拉加载
- (void)loadMoreData
{
    self.slCount++;
    //self.myDistance = self.tableView.contentOffset.y;
    NSLog(@"self.slCount = %ld",(long)self.slCount);
    NSLog(@"上拉加载");
    [self removeWorkView];
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC));
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        //请求数据
        [self postFastBDListWithPageSize:self.slCount withPages:10 withType:[NSString stringWithFormat:@"%ld",(long)self.buttonIndex]];
    });
}

- (void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"TopButtonsView" object:nil];
}

//点击最上面滚动视图 改变下面滚动视图的变化
- (void)change:(NSNotification*)notification
{
    [self.products removeAllObjects];
    [self.tableView reloadData];
    [self removeWorkView];
    NSInteger index = [notification.userInfo[@"buttonTag"] integerValue];
    self.buttonIndex = index;
    self.slCount = 1;
    NSLog(@"self.buttonIndex = %ld",(long)self.buttonIndex);
    [self postFastBDListWithPageSize:self.slCount withPages:10 withType:[NSString stringWithFormat:@"%ld",(long)self.buttonIndex]];
    [self.tableView setContentOffset:CGPointMake(0,0) animated:YES];
}

- (void)popRootVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [MobClick endLogPageView:@"UnderLinePolicyController"];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"UnderLinePolicyController"];//("PageOne"为页面名称，可自定义)
    self.titles = @[@"全部",@"有效",@"其他"];
    self.topView.buttonTitles = self.titles;
    [self.view addSubview:self.topView];
    if (!self.topView.myScrollView)
    {
        [self.topView scrollView];
    }
    [self.view addSubview:self.tableView];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(change:) name:@"TopButtonsView" object:nil];
}

#pragma mark  //获取fast保单数据列表
- (void)postFastBDListWithPageSize:(NSInteger)pageSize withPages:(NSInteger)pages withType:(NSString*)type
{
    NSDictionary* json = @{@"agentCode":[TRUserAgenCode getUserAgenCode],
                           @"pageParams":@{
                                   @"pageNum":[NSNumber numberWithInteger:pageSize],
                                   @"pageSize":[NSNumber numberWithInteger:pages]
                            },
                           @"status":type
                           };
    NSString* str = [JSONToString dictionaryToJson:json];
    MyAdditions* md5 = [[MyAdditions alloc]init];
    NSString* SStr = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    md5.str = SStr;
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@%@?sign=%@",SERVER_URL1,@"/qryInsOrderList.do",md5_Str];
    NSLog(@"MD5 = %@。转换前的md5 = %@",md5_Str,str);
    NSLog(@"url = %@",url);
    [self getFastBDListWithURL:url withParam:json];
}

- (void)getFastBDListWithURL:(NSString*)url withParam:(NSDictionary*)param
{
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstanceWithTitle:@"检测到您的设备没有连接网络!" withImageStr:@"no_record" withType:0 withFrame:CGRectMake(0, 40, UISCREENWEITH, self.tableView.frame.size.height) withVC:self];
    [networking showNetworkViewWithSuccess:^{
        self.tableView.scrollEnabled = YES;
        [self.header setHidden:NO];
        [XHNetworking POST:url parameters:param  success:^(NSData *responseObject) {
            NSLog(@"网络读取数据网络读取数据网络读取数据网络读取数据网络读取数据");
            //网络读取数据
            [self readFastBDListWithData:responseObject];
        } failure:^(NSError *error) {
            NSLog(@"error.code 线下保单列表 = %@",error.userInfo);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self endRefresh];
                [self createWorkView];
                [self.footer setHidden:YES];
            });
        }];
    } failure:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            self.tableView.scrollEnabled = NO;
            [self.header setHidden:YES];
            [self.footer setHidden:YES];
            [self endRefresh];
        });
        
    } click:^(NSInteger type) {
        NSLog(@"点击了什么类型的按钮%ld!",(long)type);
        if (type == 0)
        {
            //弹出网络提示
            
        }
    }];
    
}

- (void)createWorkView
{
    if (self.workView == nil)
    {
        self.workView = [[ShowNoNetworkView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        self.workView.labelText = @"数据加载超时,点击刷新按钮重新加载!";
        self.workView.imageName = @"no_record";
        self.workView.myType = MyTypeOfViewForShowNoLists;
        [self.workView createAllSubView];
        __weak UnderLinePolicyController* mySelf = self;
        [self.workView addActionWithBlock:^{
            //请求数据
            [mySelf postFastBDListWithPageSize:mySelf.slCount withPages:10 withType:[NSString stringWithFormat:@"%ld",(long)mySelf.buttonIndex]];
        }];
        [self.tableView addSubview:self.workView];
    }
}

- (void)removeWorkView
{
    self.workView.frame = CGRectZero;
    [self.workView removeFromSuperview];
    self.workView = nil;
}

- (void)readFastBDListWithData:(NSData*)data
{
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSString* str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"线下保单列表json = %@  线下保单列表字符串 = %@",json,str);
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        if ([json isKindOfClass:[NSDictionary class]] && json)
        {
            if ([json[@"resultCode"] isEqualToString:@"0"])
            {
                if (![json[@"responseObject"][@"insOrderList"] isKindOfClass:[NSNull class]] && json[@"responseObject"][@"insOrderList"])
                {
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        for (NSDictionary* dict in json[@"responseObject"][@"insOrderList"])
                        {
                            PolicyListModel* product = [PolicyListModel policyListWithJSON:dict];
                            [self.products addObject:product];
                        }
                        if ([json[@"responseObject"][@"page"] isKindOfClass:[NSDictionary class]] && json[@"responseObject"][@"page"])
                        {
                            //总条数
                            NSInteger i1 = [json[@"responseObject"][@"page"][@"pages"] integerValue];
                            //当前页
                            NSInteger i2 = [json[@"responseObject"][@"page"][@"pageNum"] integerValue];
                            dispatch_async(dispatch_get_main_queue(), ^{
                                
                                [self.footer setHidden:NO];
                                
                                //当刚好数据为10条、总页数只有一页时
                                if (i1 == i2)
                                {
                                    [self.tableView.footer noticeNoMoreData];
                                }
                                if ([json[@"responseObject"][@"insOrderList"] count] == 0)
                                {
                                    [self.tableView.footer noticeNoMoreData];
                                }
                            });
                        }
                    });
                }
                else
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                         [self.footer setHidden:YES];
                        
                    });
                }
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.footer setHidden:YES];
                    
                });
            }
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.footer setHidden:YES];
                
            });
        }
        //通知主线程刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            [self endRefresh];
            if (self.products.count == 0)
            {
                [self createWorkView];
            }
            else
            {
                [self removeWorkView];
            }
            [self.tableView reloadData];
        });
    });
}


/**
 *  停止刷新
 */
-(void)endRefresh
{
    if ([self.tableView.header isRefreshing])
    {
        [self.tableView.header endRefreshing];
    }
    if ([self.tableView.footer isRefreshing])
    {
        [self.tableView.footer endRefreshing];
    }
}

#pragma mark - 列表代理方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.products.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.bounds.size.height;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UISCREENWEITH, 10)];
    view.backgroundColor = F3F3F3Color;
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PolicyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil)
    {
        //直接加载 xib
        cell = [[[NSBundle mainBundle]loadNibNamed:@"PolicyCell" owner:self options:nil] lastObject];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    if (self.products.count > 0)
    {
        PolicyListModel* model = self.products[indexPath.row];
        [cell setMode:model];
        [cell setNeedsDisplay];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailPolicyController* detailPolicyVC = [[DetailPolicyController alloc]initWithNibName:@"DetailPolicyController" bundle:nil];
    PolicyListModel* model = self.products[indexPath.row];
    detailPolicyVC.insContId = model.insContId;
    detailPolicyVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailPolicyVC animated:YES];
}

@end
